import React, { useRef, useState, useEffect } from "react";
import {
    Modal,
    Form,
    Select,
    Button,
    message
} from 'antd';
import { useMappedState, useDispatch, } from 'redux-react-hook';
import { set_brokerVisible } from '../../../../../store/action/house';
import api from "../../../../../api";

const BrokerModal = (props: any) => {
    const state = useMappedState((state) => state.houseReducer);
    const dispatch = useDispatch();
    // 获取元素内容
    const form = useRef<any>(null);
    // 变量
    const [brokerList, setBrokerList] = useState<any>([]);
    // 声明周期
    useEffect(() => {
        getBrokerList()
    }, [])
    // 方法
    const getBrokerList = () => {
        api.getBrokerList().then((res: any) => {
            if (res.success) {
                setBrokerList([...res.data.data])
            }
        })
    }
    // 点击确认
    const handleOk = () => {
        dispatch(set_brokerVisible(false));
    };
    // 点击取消
    const handleCancel = () => {
        dispatch(set_brokerVisible(false));
    };
    // 点击提交
    const onFinish = (values: any) => {
        // 修改当前列的经纪人
        api.houseChange({
            id:state.delId,
            broker:values.broker
        }).then((res:any)=>{
            if(res.success) {
                message.success('修改成功');
                // 重新渲染页面
                props.getHouseList();      
                dispatch(set_brokerVisible(false));  
                form.current.resetFields()
              } else {
                message.error(res.message);
              }
        })
    };
    return (
        <>
            <Modal title={state.modalTitle} visible={state.brokerVisible} onOk={handleOk} onCancel={handleCancel}
                cancelText="关闭"
                okText="确认"
            >
                <Form
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 14 }}
                    layout="horizontal"
                    onFinish={onFinish}
                    ref={form}
                >
                    <Form.Item label="经纪人" name="broker"
                        rules={[{ required: true, message: '请选择经纪人!' }]}
                    >
                        <Select>
                            {brokerList[0] && brokerList.map((item: any) => {
                                return <Select.Option value={item.name} key={item.id}>{item.name}</Select.Option>
                            })}
                        </Select>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 20, span: 16 }}>
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
};

export default BrokerModal